package com.zzb.framework.event;

import com.zzb.framework.common.BaseResponse;
import com.zzb.framework.event.entity.SysEventNotify;
import com.zzb.framework.event.service.SysEventNotifyService;
import com.zzb.framework.log.utils.Log;
import com.zzb.framework.utils.SpringContextHolder;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 事件发布中心
 * Created by zzb on 17-2-21.
 */
public class EventHome {
    private static Logger logger = LoggerFactory.getLogger(EventHome.class);
    private static SysEventNotifyService sysEventNotifyService;
    static {
        sysEventNotifyService =  SpringContextHolder.getBean("sysEventNotifyService");

    }

    /**发布事件*/
    public  static void publishEvent(BaseEvent event){
        String eventId = event.getEventId();
        List<SysEventNotify> sysEventNotifyList = sysEventNotifyService.findByEventIdOrderByExecuteOrderAsc(eventId);
        if(CollectionUtils.isNotEmpty(sysEventNotifyList)){
            ExecutorService executors = Executors.newCachedThreadPool();
            List<CompletableFuture<BaseResponse>> futures = new ArrayList<>();
            for (SysEventNotify sysEventNotify : sysEventNotifyList) {
                executors.submit(()->{

                try {
                    Log.info("事件调用","执行事件：" + eventId);
                    String springId = sysEventNotify.getExecuteSpringId();
                    AbstractProcessor processor = SpringContextHolder.getBean(springId);
                    processor.execute(event);
                } catch (Exception e) {
                    Log.error(e.getMessage());
                }
                });

            }
            executors.shutdown();
            try {
                executors.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
